package org.example.tmsapi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            )
            .authorizeHttpRequests(authorize -> authorize
                // 允许所有静态资源访问
                .requestMatchers("/")
                    .permitAll()
                .requestMatchers("/index.html", "/dashboard.html", "/css/**", "/js/**")
                    .permitAll()
                // 允许登录API访问
                .requestMatchers("/api/auth/login")
                    .permitAll()
                // 其他所有请求需要认证
                .anyRequest()
                    .authenticated()
            )
            .formLogin(form -> form
                // 使用自定义登录页面
                .loginPage("/index.html")
                .loginProcessingUrl("/api/auth/login")
                .defaultSuccessUrl("/dashboard.html", true)
                .permitAll()
            )
            .logout(logout -> logout
                .logoutUrl("/logout")
                .logoutSuccessUrl("/index.html")
                .permitAll()
            )
            .rememberMe(rememberMe -> rememberMe
                .key("uniqueAndSecret")
                .tokenValiditySeconds(86400)
            );
        
        return http.build();
    }
    
    @Bean
    public UserDetailsService userDetailsService() {
        // 创建一个内存中的用户存储
        UserDetails admin = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("admin123")
            .roles("ADMIN")
            .build();
        
        UserDetails user1 = User.withDefaultPasswordEncoder()
            .username("user1")
            .password("password1")
            .roles("USER")
            .build();
        
        UserDetails user2 = User.withDefaultPasswordEncoder()
            .username("user2")
            .password("password2")
            .roles("USER")
            .build();
        
        return new InMemoryUserDetailsManager(admin, user1, user2);
    }
}